<script setup>
import { showToast } from "vant";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { useRoute } from "vue-router";
import { debounce } from "@/utils/debounce"
import {
  getMyOrderByUidAPI,
  DelOrderListAPI,
  fialOrderAPI,
  changeItemPriceAPI,
} from "@/server/api/itemOrders";
import { ToastFun } from "@/hook/toast";
import { dataNitkTow } from "@/hook/dataNltk";
const route = useRoute();
import { useUseStore } from "@/stores/user";
import { orderStatus } from "@/stores/payStore";
import { getJWTFun } from "@/hook/jsrsasign";
// 定义Nav导航栏数据
const NavList = ref([
  { id: -1, title: "所有订单" },
  { id: 0, title: "me.publish.pending" },
  { id: 1, title: "me.publish.toBeShipped" },
]);

import { getItemIdByUserIdAPI } from "@/server/api/userInfo"
import { getShopListAPI } from "@/server/api/ShopFollow";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const page = ref(1); // 定义切换条件
const useStore = useUseStore();
const priceShow = ref(false);
const numberPrice = ref(0);
const stateIndex = ref(-1);
const loading = ref(false);
const finished = ref(false);
const chengId = ref(0);
const router = useRouter();
const newIndex = ref(null);
const currentPage = ref(1) //第几页
const pageSize = ref(10) //每页数量
const searchQuery = ref(""); // 搜索框内容

const shopId = ref(null)

const tabList = (index) => {
  if (index !== undefined) {
    stateIndex.value = index;
  }
  allOrdersList.value = [];
  currentPage.value = 1;
  finished.value = false;
  loading.value = false;
  const data = {
    orderStatus: [stateIndex.value],
    userId: null,
    shopId: shopId.value,
    currentPage: currentPage.value,
    pageSize: pageSize.value
  }
  getMyOrderByUid(data);

};

// 定义全部订单数据
const allOrdersList = ref([]);

// 获取订单接口方法
const getMyOrderByUid = async (data) => {
  const res = await getShopListAPI(data);
  if (res.data.code === 200) {
    let data = res.data.data.list;
    console.log(data)
    allOrdersList.value.push(...data);
    if (data.length < 9) {
      finished.value = true;
    }
    loading.value = false;
  }
};

// 删除订单接口方法
const DelOrderList = async (id, index) => {
  const res = await DelOrderListAPI(id);
  showToast(res.data.data);
  allOrdersList.value.splice(index, 1);
};



//删除订单
const deleteOder = (id, index) => {
  DelOrderList(id, index);
};

// 定义跳转函数
const toDetail = (item) => {
  router.push({
    path: `/DetailShop`,
    query: { shopOrderDetail: JSON.stringify(item) },
  });
};

const onLoad = () => {
  if (finished.value) return;
  loading.value = true;
  const data = {
    orderStatus: [stateIndex.value],
    userId: null,
    shopId: shopId.value,
    currentPage: ++currentPage.value,
    pageSize: pageSize.value
  }
  getMyOrderByUid(data);
};

onMounted(() => {
  shopId.value = route.query.shopId;
  allOrdersList.value = [];
  finished.value = false;
  loading.value = false;
  const data = {
    orderStatus: [stateIndex.value],
    userId: null,
    shopId: shopId.value,
    currentPage: currentPage.value,
    pageSize: pageSize.value
  }
  getMyOrderByUid(data)
});


// 防抖函数来延迟处理搜索输入
const handleSearch = debounce(() => {
  const query = searchQuery.value.trim();

  if (!query) {
    allOrdersList.value = [];
    finished.value = false;
    loading.value = false;
    currentPage.value = 1
    const data = {
      orderStatus: [stateIndex.value],
      userId: null,
      shopId: shopId.value,
      currentPage: currentPage.value,
      pageSize: pageSize.value
    }
    getMyOrderByUid(data);
    return;
  }
  allOrdersList.value = allOrdersList.value.filter(order =>
    order.shopOrderDetail.some(product =>
      product.commodityName && product.commodityName.includes(query)
    )
  );
}, 300); // 300ms防抖

const handleClear = () => {
  shopId.value = route.query.shopId;
  allOrdersList.value = [];
  finished.value = false;
  loading.value = false;
  currentPage.value = 1
  const data = {
    orderStatus: [stateIndex.value],
    userId: null,
    shopId: shopId.value,
    currentPage: currentPage.value,
    pageSize: pageSize.value
  }
  getMyOrderByUid(data);
}

</script>

<template>
  <van-sticky>
    <top-button title="实体订单">
      <template #search>
        <van-field v-model="searchQuery" placeholder="请输入商品名称" clearable left-icon="search" @input="handleSearch"
          @clear="handleClear" />
      </template>
    </top-button>
    <div class="tab_list">
      <ul>
        <li v-for="(i, index) in NavList" :key="index" @click="tabList(i.id)" :class="{ active: stateIndex === i.id }">
          {{ $t(i.title) }}
        </li>
      </ul>
    </div>

  </van-sticky>

  <div class="itemCenter">
    <ul class="list">
      <van-list @load="onLoad" :finished="finished" :immediate-check="false" v-model:loading="loading"
        :finished-text="$t('shop.shopList.finish')">
        <li :key="index" :class="{ active: stateIndex === index }" @click="toDetail(item)"
          v-for="(item, index) in allOrdersList">
          <van-swipe-cell>
            <div class="list_hd">
              <div class="login">
                <img v-lazy="item.sellerImg" alt="" />
                {{ item.sellerName }}
              </div>


              <div class="text_right" v-if="item.orderStatus == 0">
                {{ $t("me.order.unpay") }}
              </div>
              <div class="text_right" v-if="item.orderStatus == 1">
                {{ $t("me.order.unsend") }}
              </div>
              <div class="text_right" v-else-if="item.orderStatus == 2">
                {{ $t("me.order.feedback") }}
              </div>
              <div class="text_right" v-else-if="item.orderStatus == 4">
                {{ $t("me.order.feedbacked") }}
              </div>
            </div>

            <div class="list_ad">
              <div class="imgs">
                <img v-lazy="item.commodityImg" />
              </div>

              <div class="title ellipsis-2">
                <span>{{ item.details || 'No commodity name' }}</span>

              </div>

              <div class="introduce">
                <div class="price">
                  {{ item.transactionAmount }}
                  <i>{{ item.transactionAmount ? "eCNY" : "Pi" }}</i>
                </div>

                <div class="bottom_button">
                  <div class="btn" @click.stop="toDetail(item)">
                    {{ $t("me.order.check") }}
                  </div>
                </div>
              </div>
            </div>

            <template #right v-if="false">
              <van-button square text="del" type="danger" class="delete-button"
                @click="deleteOder(item.orderId, index)" />
            </template>
          </van-swipe-cell>
        </li>
      </van-list>
    </ul>
  </div>
</template>

<style lang="scss" scoped>
.fixe {
  width: 100vw;
  height: 140rem;
  background-color: #fff;

  .top {
    position: fixed;
    width: 100vw;
    height: 140rem;
    background-color: #ffffff;
  }
}

.tab_list {
  padding-top: 60rem;

  ul {
    background-color: #f5f5f5;
    display: flex;
    justify-content: space-around;
    padding: 15rem 10rem;

    li {
      font-size: 15rem;
      position: relative;
      color: #ccc;
      font-weight: 600;

      &::after {
        position: absolute;
        bottom: -10rem;
        display: none;
        content: "";
        background-color: #642e8e;
        width: 20rem;
        height: 3rem;
        left: 50%;
        transform: translateX(-50%);
        border-radius: 10rem;
      }

      &:hover {
        color: #642e8e;

        &::after {
          display: block;
          color: #642e8e;
        }
      }

      &.active {
        color: #642e8e;

        &::after {
          display: block;
        }
      }
    }
  }
}

.itemCenter {
  font-size: 14rem;
  height: 100vh;
  background-color: #f5f5f5;
  box-sizing: border-box;
  width: 100%;

  .list {
    background-color: #f5f5f5;

    li {
      border: 10rem solid #fff;

      margin-top: 10rem;
      background-color: #fff;

      :deep(.delete-button) {
        height: 100%;
      }

      .list_hd {
        display: flex;
        justify-content: space-between;
        height: 20rem;
        padding: 10rem 0;

        .login {
          display: flex;
          align-items: center;
          height: 24rem;
          color: #000000;
          font-weight: 500;
          font-size: 16rem;

          img {
            margin-right: 10rem;
            width: 24rem;
            height: 24rem;
            /* 固定高度 */
            object-fit: cover;
            vertical-align: middle;
            border-radius: 50%;
          }
        }

        .text_right {
          color: #642e8e;
          font-size: 16rem;
        }
      }

      .list_ad {
        display: flex;
        margin-top: 5rem;

        .imgs {
          width: 70rem;
          height: 70rem;
          overflow: hidden;

          border-radius: 10rem;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }


        .title {
          margin-left: 20rem;
          width: 170rem;
          height: 72rem;
          font-size: 14rem;
          line-height: 26rem;

          display: flex;
          justify-content: space-between;
          flex-direction: column;

          >span:nth-of-type(1) {
            white-space: nowrap;
            text-overflow: ellipsis;
          }
        }

        .introduce {
          display: flex;
          flex-direction: column;
          padding-left: 20rem;

          .price {
            white-space: nowrap;
            margin: 0rem 5rem 20rem auto;
            font-size: 16rem;
            font-weight: 600;
            color: rgb(0, 0, 0);

            >i {
              color: #000000;
              font-size: 12rem;
            }
          }

          .bottom_button {
            margin-left: auto;
            display: flex;

            .btn {
              padding: 2rem 20rem;
              width: 48rem;
              margin-left: 10rem;
              font-size: 12rem;
              height: 30rem;
              line-height: 30rem;
              text-align: center;
              border-radius: 20rem;
              background-color: #642e8e;
              color: #fff;
            }
          }
        }
      }
    }
  }
}
</style>
